package com.freestyle.seatabusiness.order.service;

import com.freestyle.seatabusiness.api.models.Order;
import com.freestyle.seatabusiness.api.service.AccountService;
import com.freestyle.seatabusiness.api.service.OrderService;
import com.freestyle.seatabusiness.api.service.StockService;
import com.freestyle.seatabusiness.order.dao.OrderTblMapper;
import com.freestyle.seatabusiness.order.entity.OrderTbl;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;

import javax.annotation.Resource;

/**
 * Created by rocklee on 2021/12/16 17:07
 */
@DubboService
public class OrderServiceImp implements OrderService {
  @Resource
  private OrderTblMapper orderTblMapper;
  @DubboReference
  private AccountService accountService;
  @DubboReference
  private StockService stockService;

  @GlobalTransactional
  @Override
  public Order create(String userId, String commodityCode, int orderCount) {
    int orderMoney=200 * orderCount; //订单金额
    accountService.debit(userId,orderMoney); //帐户余额扣款
    stockService.deduct(commodityCode,orderCount); //库存扣数
    OrderTbl orderTbl=new OrderTbl(userId,commodityCode,orderCount,orderMoney);
    if (orderTblMapper.insert(orderTbl)<1){
      throw new RuntimeException("建立订单失败.");
    }
    Order order=new Order();
    BeanUtils.copyProperties(orderTbl,order);
    return order;
  }
}
